//
//  DropMenuView.m
//  DebugDemo
//
//  Created by XFB on 2019/1/19.
//  Copyright © 2019年 ZhouCheng. All rights reserved.
//

#import "DropMenuView.h"
#import "CoverView.h"

@interface DropMenuView ()

@property (nonatomic, strong) NSMutableArray *menuButtons;
@property (nonatomic, strong) NSMutableArray *separateLines;
@property (nonatomic, strong) NSMutableArray *controllers;
@property (nonatomic, strong) NSMutableArray *columsHeight;

@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) CoverView *coverView;

@property (nonatomic, weak) UIView *bottomLineView;
@property (nonatomic, weak) id observer;

@end

@implementation DropMenuView

- (NSMutableArray *)separateLines
{
    if (_separateLines == nil) {
        _separateLines = @[].mutableCopy;
    }
    return _separateLines;
}

- (NSMutableArray *)menuButtons
{
    if (_menuButtons == nil) {
        _menuButtons = @[].mutableCopy;
    }
    return _menuButtons;
}

- (NSMutableArray *)columsHeight
{
    if (_columsHeight == nil) {
        _columsHeight = @[].mutableCopy;
    }
    return _columsHeight;
}

- (NSMutableArray *)controllers
{
    if (_controllers == nil) {
        _controllers = @[].mutableCopy;
    }
    return _controllers;
}

- (CoverView *)coverView
{
    if (_coverView == nil) {
        CGFloat coverX = 0;
        CGFloat coverY = CGRectGetMaxY(self.frame);
        CGFloat coverW = self.width;
        CGFloat coverH = self.superview.bounds.size.height - coverY;
        _coverView = [[CoverView alloc] initWithFrame:CGRectMake(coverX, coverY, coverW, coverH)];
        _coverView.backgroundColor = _coverColor;
        [self.superview addSubview:_coverView];
        
        __weak typeof(self) weakSelf = self;
        _coverView.coverViewBlock = ^{
            [weakSelf dismiss];
        };
    }
    return _coverView;
}

- (UIView *)contentView
{
    if (_contentView == nil) {
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = [UIColor whiteColor];
        _contentView.frame = CGRectMake(0, 0, self.width, 0);
        _contentView.clipsToBounds = YES;
        [self.coverView addSubview:_contentView];
    }
    return _contentView;
}


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI
{
    self.backgroundColor = [UIColor whiteColor];
    _separateLineViewTopMargin = 10;
    _separateLineViewColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1];
    _coverColor = [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:0.7];
    
    _observer = [[NSNotificationCenter defaultCenter] addObserverForName:@"UpdateMenuTitleNote" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
       
        /// 获取列
        NSInteger colum = [self.controllers indexOfObject:note.object];
        
        /// 获取对应的按钮
        UIButton *button = self.menuButtons[colum];
        
        /// 隐藏下拉菜单
        [self dismiss];
        
        /// 获取所有的值
        NSArray *allValues = note.userInfo.allValues;
        
        /// 不需要设置标题,字典个数大于1、或者有数组
        if (allValues.count > 1 ||
            [allValues.firstObject isKindOfClass:[NSArray class]]) {
            return ;
        }
        
        [button setTitle:allValues.firstObject forState:UIControlStateNormal];
    }];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    NSInteger count = self.menuButtons.count;
    
    /// 布局子控件
    CGFloat buttonX = 0;
    CGFloat buttonY = 0;
    CGFloat buttonW = self.width/count;
    CGFloat buttonH = self.height;
    
    for (NSInteger i = 0; i < count; i ++) {
        /// 设置按钮的位置
        UIButton *button = self.menuButtons[i];
        buttonX = i * buttonW;
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
        /// 设置分割线的位置
        if (i < count-1) {
            UIView *separateLine = self.separateLines[i];
            separateLine.frame = CGRectMake(CGRectGetMaxX(button.frame), _separateLineViewTopMargin, 1, buttonH-2*_separateLineViewTopMargin);
        }
    }
    
    /// 设置底部view的位置
    CGFloat bottomX = 0;
    CGFloat bottomH = 1;
    CGFloat bottomY = buttonH - bottomH;
    CGFloat bottomW = self.width;
    _bottomLineView.frame = CGRectMake(bottomX, bottomY, bottomW, bottomH);
}

- (void)dismiss
{
    /// 下拉菜单弹回
    for (UIButton *button in self.menuButtons) {
        button.selected = NO;
    }
    
    /// 移除蒙版
    self.coverView.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0];
    __weak typeof(self) weakSelf = self;

    [UIView animateWithDuration:0.25 animations:^{
        CGRect frame = self.contentView.frame;
        frame.size.height = 0;
        self.contentView.frame = frame;
    } completion:^(BOOL finished) {
        self.coverView.hidden = YES;
        self.coverView.backgroundColor = weakSelf.coverColor;
    }];
}

/// 即将进入窗口
- (void)willMoveToWindow:(UIWindow *)newWindow
{
    [super willMoveToWindow:newWindow];
    [self reloadView];
}

- (void)reloadView
{
    /// 删除之前所有数据，移除之前所有子控件
    [self clearSubViews];
    
    /// 没有数据源，直接返回
    if (self.dataSource == nil) return;
    
    /// 判断之前是否添加过。添加过了就不添加了
    if (self.menuButtons.count) return;
    
    /// 判断有没有实现 numberOfColumsInMemu:
    if (![self.dataSource respondsToSelector:@selector(numberOfColumsInMemu:)]) {
        @throw [NSException exceptionWithName:@"ERROR" reason:@"未实现（numberOfColsInMenu:）" userInfo:nil];
    }
    
    /// 判断有没有实现 dropMenuView:buttonForColumAtIndex:
    if (![self.dataSource respondsToSelector:@selector(dropMenuView:buttonForColumAtIndex:)]) {
        @throw [NSException exceptionWithName:@"ERROR" reason:@"未实现(dropMenuView:buttonForColumAtIndex:)" userInfo:nil];
    }
    
    /// 判断有没有实现 dropMenuView:viewControllerForColumAtIndex:
    if (![self.dataSource respondsToSelector:@selector(dropMenuView:viewControllerForColumAtIndex:)]) {
        @throw [NSException exceptionWithName:@"ERROR" reason:@"未实现(dropMenuView:viewControllerForColumAtIndex:)" userInfo:nil];
    }
    
    /// 判断有没有实现
    if (![self.dataSource respondsToSelector:@selector(drppMenuView:heightForColumAtIndex:)]) {
        @throw [NSException exceptionWithName:@"ERROR" reason:@"未实现(drppMenuView:heightForColumAtIndex:)" userInfo:nil];
    }
    
    /// 获取有多少列
    NSInteger colums = [self.dataSource numberOfColumsInMemu:self];
    
    /// 没有列直接返回
    if (colums == 0) return;
    
    /// 添加按钮
    for (NSInteger colum = 0; colum < colums; colum ++) {
        /// 获取按钮
        UIButton *menuButton = [self.dataSource dropMenuView:self buttonForColumAtIndex:colum];
        menuButton.tag = colum;
        [menuButton addTarget:self action:@selector(menuButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        
        if (menuButton == nil) {
            @throw [NSException exceptionWithName:@"ERROR" reason:@"dropMenuView:buttonForColumAtIndex:这个方法不能返回空的按钮" userInfo:nil];
            return;
        }
        [self addSubview:menuButton];
        
        /// 添加按钮
        [self.menuButtons addObject:menuButton];
        
        /// 保存所有列的高度
        CGFloat height = [self.dataSource drppMenuView:self heightForColumAtIndex:colum];
        [self.columsHeight addObject:@(height)];
        
        /// 保存所有子控制器
        UIViewController *vc = [self.dataSource dropMenuView:self viewControllerForColumAtIndex:colum];
        [self.controllers addObject:vc];
    }
 
    /// 添加分割线
    NSInteger count = colums - 1;
    for (NSInteger i = 0; i < count; i ++) {
        UIView *separateLine = [[UIView alloc] init];
        separateLine.backgroundColor = _separateLineViewColor;
        [self addSubview:separateLine];
        [self.separateLines addObject:separateLine];
    }
    
    /// 添加底部View
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = _separateLineViewColor;
    _bottomLineView = bottomView;
    [self addSubview:bottomView];
    
    /// 设置所有子控件的尺寸
    [self layoutSubviews];
}

- (void)menuButtonDidClick:(UIButton *)button
{
    button.selected = !button.selected;
    
    for (UIButton *otherButton in self.menuButtons) {
        if (otherButton.selected == YES) {
            otherButton.selected = NO;
        }
    }
    
    if (button.selected == YES) { //当按钮选中，弹出蒙版
        /// 添加蒙版
        self.coverView.hidden = NO;
        
        /// 获取角标
        NSInteger i = button.tag;
        
        /// 移除之前的子控制器的view
        [self.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

        /// 添加对应的子控制器View
        UIViewController *vc = self.controllers[i];
        vc.view.frame = self.contentView.bounds;
        [self.contentView addSubview:vc.view];
        
        /// 设置内容的高度
        CGFloat height = [self.columsHeight[i] floatValue];
        
        [UIView animateWithDuration:0.25 animations:^{
            CGRect frame = self.contentView.frame;
            frame.size.height = height;
            self.contentView.frame = frame;
        }];
    } else { /// 当前按钮未选中，收回蒙版
        [self dismiss];
    }
}

- (void)clearSubViews
{
    self.bottomLineView = nil;
    self.coverView = nil;
    self.contentView = nil;
    
    [self.separateLines removeAllObjects];
    [self.menuButtons removeAllObjects];
    [self.controllers removeAllObjects];
    [self.columsHeight removeAllObjects];
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
    
    [[NSNotificationCenter defaultCenter] removeObserver:_observer];
}

@end
